
var CheckBoxList = {

	outputJSON:true,
	sizes:{
		divWidth:200,
		divHeight:300,
		closeWidth:200,
		closeHeight:20
	},
	showBtnClose:true,
	zIndex:{
		main_div:2500,
		background_div:1000
	},

	params:{},
	selectedAll:false,

	Load:function () {
		CheckBoxList.addHandler(window, 'load', function () {
			var elems = document.body.getElementsByTagName('select');
			for (var i = 0; i < elems.length; i++) {
				if (elems[i].className.indexOf('checkList') != 0) continue;
				if (!elems[i].paramName) {
					CheckBoxList.Init(elems[i]);
				}
			}
		});

	},

	searchForm:function (obj) {
		if (obj.parentNode.nodeName == 'BODY') return false;

		if (obj.parentNode.nodeName == 'FORM') {
			return obj.parentNode;
		} else {
			return CheckBoxList.searchForm(obj.parentNode);
		}
	},

	Init:function (select_obj) {

		var paramName = select_obj.name;

		var paramId = select_obj.id;
		if (!paramId) {
			paramId = paramName;
		}

		select_obj.id = paramId + '_select';
		select_obj.paramName = paramName;

		var form_input = document.createElement('div');
		form_input.style.display = 'none';
		form_input.id = paramId + '_finput';
		select_obj.parentNode.insertBefore(form_input, select_obj);

		var input_obj = document.createElement('input');
		input_obj.className = select_obj.className;
		input_obj.style.width = select_obj.offsetWidth - 2 + 'px';
		input_obj.style.height = select_obj.offsetHeight - 2 + 'px';
		input_obj.style.cursor = 'default';
		input_obj.paramName = paramName;
		input_obj.paramId = paramId;
		input_obj.readOnly = 'readonly';
		input_obj.id = paramId + '_input';

		input_obj.onclick = function(){
			var self = this;
			CheckBoxList.inClick(self);
		};


		select_obj.style.display = 'none';
		select_obj.parentNode.insertBefore(input_obj, select_obj);
		select_obj.name = '';

		CheckBoxList.Refresh(paramId);

	},

	inClick: function (obj) {
		var div;
		if (document.getElementById(this.paramId + '_div') == undefined) {
			CheckBoxList.showBG(true);

			div = document.createElement('div');
			div.className = 'checkList';
			div.id = obj.paramId + '_div';
			div.paramName = obj.paramName;
			div.paramId = obj.paramId;
			div.style.zIndex = CheckBoxList.zIndex.main_div;

			div.style.top = (CheckBoxList.screenSize().h - (CheckBoxList.findPosY(obj) + obj.offsetHeight + CheckBoxList.sizes.divHeight)) > 0 ? (CheckBoxList.findPosY(obj) + obj.offsetHeight) + 'px' : (CheckBoxList.findPosY(obj) - CheckBoxList.sizes.divHeight) - 4 + 'px';

			div.style.left = (CheckBoxList.screenSize().w - (CheckBoxList.findPosX(obj) + obj.offsetWidth + CheckBoxList.sizes.divWidth)) > 0 ? CheckBoxList.findPosX(obj) + 'px' : (CheckBoxList.findPosX(obj) - CheckBoxList.sizes.divWidth) - 4 + 'px';

			div.style.width = CheckBoxList.sizes.divWidth + 'px';
			div.style.height = CheckBoxList.sizes.divHeight + 'px';

			var check_list = document.createElement('div');
			check_list.style.width = CheckBoxList.sizes.divWidth + 'px';
			check_list.style.height = (CheckBoxList.sizes.divHeight - (CheckBoxList.showBtnClose ? CheckBoxList.sizes.closeHeight + 2 : 0)) + 'px';

			var select_obj = document.getElementById(obj.paramId + '_select');

			var label, checkbox;
			for (var i = 0; i < select_obj.options.length; i++) {
				label = document.createElement('label');
				checkbox = document.createElement('input');
				checkbox.type = 'checkbox';
				checkbox.defaultChecked  = (
						CheckBoxList.arraySearch(select_obj.options[i].value, CheckBoxList.params[div.paramId]) !== false
						|| (CheckBoxList.selectedAll && select_obj.options[i].value == '')
					);

				checkbox.name = div.paramName + '[]';
				checkbox.paramName = div.paramName;
				checkbox.paramId = div.paramId;
				checkbox.value = select_obj.options[i].value;

				checkbox.onclick = function(){
					var self = this;
					CheckBoxList.cbChange(self);
				};

				label.appendChild(checkbox);
				label.appendChild(document.createTextNode(' ' + select_obj.options[i].text));
				label.appendChild(document.createElement('br'));

				check_list.appendChild(label);
			}

			div.appendChild(check_list);

			if (CheckBoxList.showBtnClose) {
				var closeBtn = document.createElement('input');
				closeBtn.type = 'button';
				closeBtn.style.width = CheckBoxList.sizes.closeWidth + 'px';
				closeBtn.style.height = CheckBoxList.sizes.closeHeight + 'px';
				closeBtn.value = 'Применить';
				closeBtn.onclick = function () {
					var elems = document.body.getElementsByTagName('div');
					for (var i = 0; i < elems.length; i++) {
						if (elems[i].className != 'checkList') continue;
						elems[i].style.display = 'none';
					}

					CheckBoxList.showBG(false);
				};
				div.appendChild(closeBtn);
			}

			document.body.appendChild(div);

		} else {
			div = document.getElementById(obj.paramId + '_div');
			div.style.display = div.style.display == 'none' ? '' : 'none';

			CheckBoxList.showBG(div.style.display != 'none');
		}


	},

	cbChange:function(obj){
		if (obj.value == '') {
			var elem = document.getElementsByName(obj.name);
			for (var i = 0; i < elem.length; i++) {
				if (elem[i].value == '' || elem[i].type != 'checkbox') continue;
				if (elem[i].paramId != obj.paramId) continue;

				elem[i].checked = obj.checked;
				CheckBoxList.checked(elem[i], true);
			}
			alert(obj.paramId);
			CheckBoxList.Refresh(obj.paramId);
		} else {
			CheckBoxList.checked(obj);
		}
	},

	Refresh:function (paramId) {

		var select_obj = document.getElementById(paramId + '_select');
		var inputSelect = document.getElementById(paramId + '_input');

		inputSelect.value = '';

		var form_input = document.getElementById(paramId + '_finput');
		form_input.innerHTML = '';

		CheckBoxList.selectedAll = true;

		for (var i = 0; i < select_obj.options.length; i++) {
			if (select_obj.options[i].value == '') continue;
			if (CheckBoxList.arraySearch(select_obj.options[i].value, CheckBoxList.params[paramId]) !== false) {
				inputSelect.value += select_obj.options[i].text + ',';
				if (!CheckBoxList.outputJSON) {
					form_input.innerHTML += '<input type="hidden" name="' + inputSelect.paramName + '[]" value="' + select_obj.options[i].value + '">';
				}
			} else {
				CheckBoxList.selectedAll = false;
			}
		}
		if (CheckBoxList.outputJSON){
			var hidden_out = document.createElement('input');
			hidden_out.type = 'hidden';
			hidden_out.name = inputSelect.paramName;
			hidden_out.value = CheckBoxList.arrayToJSON(CheckBoxList.params[paramId]);
			form_input.appendChild(hidden_out);
		}

		inputSelect.value = substr(inputSelect.value, 0, -1);

		var selectWidth = inputSelect.offsetWidth;
		var selectFontSize = parseInt(CheckBoxList.getStyle(inputSelect, 'font-size'));

		var lengthLimit = 10;
		if (selectFontSize && selectWidth) {
			var lenLim = Math.floor(selectWidth / selectFontSize / 1.4);
			if (lenLim > lengthLimit) lengthLimit = lenLim;
		}


		if (inputSelect.value.length > lengthLimit) inputSelect.value = substr(inputSelect.value, 0, lengthLimit) + '..';

	},

	showBG:function (state) {
		var bg_div = document.getElementById('checkList_bg');
		if (bg_div == undefined) {
			bg_div = document.createElement('div');
			bg_div.style.height = '100%';
			bg_div.style.width = '100%';
			bg_div.style.top = '0';
			bg_div.style.left = '0';
			bg_div.id = 'checkList_bg';
			bg_div.style.position = 'fixed';
			bg_div.style.overflow = 'auto';
//			bg_div.style.backgroundColor = 'none';
			bg_div.style.zIndex = CheckBoxList.zIndex.background_div;
			bg_div.style.display = state ? '' : 'none';
			bg_div.onclick = function () {
				var self = this;
				var elems = document.body.getElementsByTagName('div');
				for (var i = 0; i < elems.length; i++) {
					if (elems[i].className != 'checkList') continue;
					elems[i].style.display = 'none';
				}
				self.style.display = 'none';
			};

			document.body.appendChild(bg_div);
		} else {
			bg_div.style.display = state ? '' : 'none';
		}
	},

	checked:function (checkbox, not_refresh) {
		var paramId = checkbox.paramId;
		var index = CheckBoxList.arraySearch(checkbox.value, CheckBoxList.params[paramId]);

		if (!CheckBoxList.params[paramId]) CheckBoxList.params[paramId] = new Array;
		if (checkbox.checked === true) {
			if (index === false) {
				CheckBoxList.params[paramId].push(checkbox.value);
			}
		} else {
			CheckBoxList.params[paramId].splice(index, 1);
		}
		if (!not_refresh) CheckBoxList.Refresh(paramId);
	},

//	HELPERS

	arrayToJSON:function (array) {
		if (typeof array !== 'object') return '[]';

		var result = '[';
		if (array.length){
			for (var i = 0; i < array.length; i++) {
				if (typeof array[i] === 'string') result += '"';
				result += array[i];
				if (typeof array[i] === 'string') result += '"';
				result += ',';
			}
			result = substr(result, 0, -1);
		}
		result += ']';

		return result;
	},

	arraySearch:function(needle, haystack){
		for (var key in haystack)
			if (haystack.hasOwnProperty(key) && haystack[key] == needle) {
				return key;
			}
		return false;
	},

	screenSize:function () {
		var w, h; // Объявляем переменные, w - длина, h - высота
		w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
		h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
		return {w:w, h:h};
	},

	findPosX:function (obj) {
		var curleft = 0;
		if (obj.offsetParent) {
			while (1) {
				curleft += obj.offsetLeft;
				if (!obj.offsetParent) {
					break;
				}
				obj = obj.offsetParent;
			}
		} else if (obj.x) {
			curleft += obj.x;
		}
		return curleft;
	},

	findPosY:function (obj) {
		var curtop = 0;
		if (obj.offsetParent) {
			while (1) {
				curtop += obj.offsetTop;
				if (!obj.offsetParent) {
					break;
				}
				obj = obj.offsetParent;
			}
		} else if (obj.y) {
			curtop += obj.y;
		}
		return curtop;
	},

	getStyle:function (el, style) {
		if (!document.getElementById) return null;
		var value = el.style[CheckBoxList.toCamelCase(style)];

		if (!value) {
			if (document.defaultView) {
				value = document.defaultView.getComputedStyle(el, "").getPropertyValue(style);
			}

			else if (el.currentStyle) {
				value = el.currentStyle[CheckBoxList.toCamelCase(style)];
			}
		}

		return value;
	},

	toCamelCase:function (sInput) {
		var oStringList = sInput.split('-');
		if (oStringList.length == 1) {
			return oStringList[0];
		}
		var ret = sInput.indexOf("-") == 0 ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) : oStringList[0];
		for (var i = 1, len = oStringList.length; i < len; i++) {
			var s = oStringList[i];
			ret += s.charAt(0).toUpperCase() + s.substring(1)
		}
		return ret;
	},

	addHandler:function (object, event, handler) {
		if (typeof object.addEventListener != 'undefined') {
			object.addEventListener(event, handler, false);
		} else if (typeof object.attachEvent != 'undefined') {
			object.attachEvent('on' + event, handler);
		} else {
			throw "Incompatible browser";
		}
	}

};

//PHP functions analogs for JavaScript


function substr(f_string, f_start, f_length) {
	if (f_start < 0) {
		f_start += f_string.length;
	}

	if (f_length == undefined) {
		f_length = f_string.length;
	} else if (f_length < 0) {
		f_length += f_string.length;
	} else {
		f_length += f_start;
	}

	if (f_length < f_start) {
		f_length = f_start;
	}

	return f_string.substring(f_start, f_length);
}


function rand(min, max) {
	if (max) {
		return Math.floor(Math.random() * (max - min + 1)) + min;
	} else {
		return Math.floor(Math.random() * (min + 1));
	}
}
